package com.jlastu.znb.presenter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import com.jlastu.znb.base.WeakRefHandler;
import com.jlastu.znb.contract.MainContract;
import com.jlastu.znb.entity.Goods;
import com.jlastu.znb.entity.Photo;

import java.util.ArrayList;
import java.util.List;

public class BuyerHomePresenter implements MainContract.IMainPresenter {

    private static final int WHAT_GET_GOODS_LIST = 0;
    private static final int WHAT_SHOW_ALL_GOODS = 0; // 用于区分消息类型
    private static final int WHAT_SHOW_CATEGORY_GOODS = 1;
    private MainContract.IMainView mMainView;
    private Context mContext;
    private Handler mHandler;

    public BuyerHomePresenter(MainContract.IMainView mainView, Context context) {
        mMainView = mainView;
        mContext = context;
        mHandler = new WeakRefHandler<>(Looper.getMainLooper(), this, new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message msg) {
                switch (msg.what) {
                    case WHAT_GET_GOODS_LIST:
                        @SuppressWarnings("unchecked")
                        List<Goods> goodsList = (List<Goods>) msg.obj;
                        if (msg.arg1 == WHAT_SHOW_ALL_GOODS) {
                            mMainView.showGoodsList(goodsList);
                        } else if (msg.arg1 == WHAT_SHOW_CATEGORY_GOODS) {
                            mMainView.showGoodsByCategory(goodsList);
                        }
                        break;
                }
                return true;
            }
        });
    }

    @Override
    public void getGoodsList() {
        List<Goods> list = new ArrayList<>();
        new Thread(new Runnable() {
            @SuppressLint("Range")
            @Override
            public void run() {
                //此处异步进行数据查询
                //Uri uri = Uri.parse("content://com.jlastu.znb.provider/goods/1");
                Uri uri = Uri.parse("content://com.jlastu.znb.provider/goods");
                Cursor cursor = mContext.getContentResolver().query(
                        uri, null, null, null);

                try {
                    if (cursor != null && cursor.moveToFirst()) {
                        do {
                            Goods goods = new Goods();
                            int goods_id = cursor.getInt(cursor.getColumnIndex("_id"));
                            goods.setId(goods_id);
                            goods.setName(cursor.getString(cursor.getColumnIndex("goods_name")));
                            goods.setPrice(cursor.getDouble(cursor.getColumnIndex("goods_price")));
                            goods.setUnit(cursor.getString(cursor.getColumnIndex("goods_unit")));
                            goods.setBrowseCount(cursor.getInt(cursor.getColumnIndex("goods_browse")));
                            goods.setMessage(cursor.getString(cursor.getColumnIndex("goods_message")));
                            goods.setCategory(cursor.getString(cursor.getColumnIndex("category")));
                            Log.d("TAG", "run: " + mContext);
                            Uri photoUri = Uri.parse("content://com.jlastu.znb.provider/photo");
                            Cursor photoCursor = mContext.getContentResolver().query(
                                    photoUri,
                                    null,
                                    "goods_id = ?",
                                    new String[]{String.valueOf(goods_id)},
                                    null);

                            if (photoCursor != null && photoCursor.moveToFirst()) {
                                do {
                                    Photo photo = new Photo();
                                    photo.setId(photoCursor.getInt(photoCursor.getColumnIndex("_id")));
                                    photo.setData(photoCursor.getBlob(photoCursor.getColumnIndex("image")));
                                    goods.addPhoto(photo);
                                } while (photoCursor.moveToNext());
                            }
                            Log.d("", "goods ====== " + goods.toString());
                            list.add(goods);
                        } while (cursor.moveToNext());
                    }
                } finally {
                    if (cursor != null) {
                        cursor.close();
                    }
                }
                Uri photoUri = Uri.parse("content://com.jlastu.znb.provider/photo");
                Cursor photoCursor = mContext.getContentResolver().query(
                        photoUri, null, null, null);
                if (photoCursor != null && photoCursor.moveToFirst()) {
                    do {
                        Log.d("", "photo_id = " + photoCursor.getInt(cursor.getColumnIndex("_id")));
                        Log.d("", "photo_miage = " + photoCursor.getBlob(2));
                    } while (photoCursor.moveToNext());
                }
                //子线程通过Handler发送消息，完成线程之间的通信。
                Message message = Message.obtain();
                message.obj = list;
                message.what = WHAT_GET_GOODS_LIST;
                mHandler.sendMessage(message);
            }
        }).start();
    }

    public void getGoodsByCategory(String category) {
        List<Goods> list = new ArrayList<>();
        new Thread(new Runnable() {
            @SuppressLint("Range")
            @Override
            public void run() {
                // 此处异步进行数据查询
                Uri uri = Uri.parse("content://com.jlastu.znb.provider/goods_by_category/" + category);
                Log.d("TAG", "run: " + category);
                Cursor cursor = mContext.getContentResolver().query(
                        uri, null, "category = ?", new String[]{category}, null);
                Log.d("TAG", "run3: " + cursor);
                Log.d("TAG", "run2: " + cursor.moveToFirst());
                try {
                    if (cursor != null && cursor.moveToFirst()) {
                        Log.d("TAG", "run3: " + cursor);
                        do {
                            Goods goods = new Goods();
                            int goods_id = cursor.getInt(cursor.getColumnIndex("_id"));
                            goods.setId(goods_id);
                            goods.setName(cursor.getString(cursor.getColumnIndex("goods_name")));
                            goods.setPrice(cursor.getDouble(cursor.getColumnIndex("goods_price")));
                            goods.setUnit(cursor.getString(cursor.getColumnIndex("goods_unit")));
                            goods.setBrowseCount(cursor.getInt(cursor.getColumnIndex("goods_browse")));
                            goods.setMessage(cursor.getString(cursor.getColumnIndex("goods_message")));
                            Log.d("TAG", "run4: " + mContext);

                            Uri photoUri = Uri.parse("content://com.jlastu.znb.provider/photo");
                            String photoSelection = "goods_id = ?";
                            String[] photoSelectionArgs = new String[]{String.valueOf(goods_id)};
                            Cursor photoCursor = mContext.getContentResolver().query(
                                    photoUri,
                                    null,
                                    photoSelection,
                                    photoSelectionArgs,
                                    null);

                            if (photoCursor != null && photoCursor.moveToFirst()) {
                                do {
                                    Photo photo = new Photo();
                                    photo.setId(photoCursor.getInt(photoCursor.getColumnIndex("_id")));
                                    photo.setData(photoCursor.getBlob(photoCursor.getColumnIndex("image")));
                                    goods.addPhoto(photo);
                                } while (photoCursor.moveToNext());
                            }
                            Log.d("", "goods ====== " + goods.toString());
                            list.add(goods);
                        } while (cursor.moveToNext());
                    } else {
                        Log.d("TAG", "run: " + 123);
                    }

                } finally {
                    if (cursor != null) {
                        cursor.close();
                    }
                }
                // 子线程通过Handler发送消息，完成线程之间的通信。
                Message message = Message.obtain();
                message.obj = list;
                message.what = WHAT_GET_GOODS_LIST;
                mHandler.sendMessage(message);
            }
        }).start();
    }

    private String[] getGoodsIds(List<Goods> goodsList) {
        String[] ids = new String[goodsList.size()];
        for (int i = 0; i < goodsList.size(); i++) {
            ids[i] = String.valueOf(goodsList.get(i).getId());
        }
        return ids;
    }
}
   /*Handler mHandler = new WeakRefHandler<>(Looper.getMainLooper(), this, new Handler.Callback() {
      @Override
      public boolean handleMessage(@NonNull Message msg) {
         int what = msg.what;
         switch (what) {
            case WHAT_GET_GOODS_LIST:
               mMainView.showGoodsList((List<Goods>) msg.obj);
               break;
         }
         return false;
      }
   });
   private Handler mHandler = new Handler(Looper.getMainLooper()) {
      @Override
      public void handleMessage(Message msg) {
         if (msg.what == WHAT_GET_GOODS_LIST) {
            List<Goods> goodsList = (List<Goods>) msg.obj;
            // 更新UI，例如刷新RecyclerView
            mMainView.showGoodsByCategory(goodsList);
         }
      }
   };*/

